<template>
  <el-form>
    <el-row>
      <el-col :span="12">
        <el-radio-group v-model="tabPosition">
          <el-radio-button value="0">结算单详情</el-radio-button>
          <el-radio-button
            v-if="queryParams.action === 'view'"
            value="1"
            @click="getExamineTableData()"
            >审批记录</el-radio-button
          >
          <el-radio-button v-if="queryParams.action === 'examine'" value="2">
            {{ examineName() }}
          </el-radio-button>
        </el-radio-group>
      </el-col>
      <el-col :span="12" style="text-align: right">
        <el-button
          v-if="queryParams.action === 'add' || queryParams.action === 'edit'"
          color="#1E3485"
          @click="submitForm(stlmtReconRef)"
          >保存</el-button
        >
        <el-button
          v-if="queryParams.action === 'add' || queryParams.action === 'edit'"
          style="display: none"
          color="#1E3485"
          @click="saveOrSubmit(stlmtReconRef)"
          >保存并提交</el-button
        >
        <closeTagButton id="closeTagButtonRef" />
      </el-col>
    </el-row>
    <!-- 结算单详情 -->
    <div v-if="tabPosition === '0'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>基本信息</template>
        <el-form
          ref="stlmtReconRef"
          label-width="180px"
          :model="stlmtReconModel"
          :rules="rules"
        >
          <el-row>
            <el-col :span="24">
              <el-form-item label="销售合同" required prop="contractName">
                <el-input
                  v-model="stlmtReconModel.contractName"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                  @click="showProjectSelectDialog"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="结算日期" required prop="settlementDate">
                <el-date-picker
                  v-model="stlmtReconModel.settlementDate"
                  type="date"
                  value-format="YYYY-MM-DD"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="历史结算金额">
                <el-input
                  v-model="stlmtReconModel.historySettlementAmount"
                  disabled
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="采购单位">
                <el-input v-model="stlmtReconModel.purchaseDeptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称">
                <el-input v-model="stlmtReconModel.projectName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="供货单位">
                <el-input v-model="stlmtReconModel.supplyDeptName" disabled />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="生产厂家">
                <el-input v-model="stlmtReconModel.supplierDeptName" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="备注">
                <el-input
                  v-model="stlmtReconModel.mark"
                  type="textarea"
                  :rows="1"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="结算对账单">
                <el-button
                  color="#1E3485"
                  :disabled="
                    queryParams.action != 'add' && queryParams.action != 'edit'
                  "
                  @click="showReconciliationSelectDialog"
                  >选择对账订单</el-button
                >
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="reconcoloationTableData"
          :loading="reconcoloationTableLoading"
          size="mini"
          style="margin-left: 180px"
        >
          <vxe-column type="seq" title="序号" width="50" align="center" />
          <vxe-column
            v-for="column in reconcoloationTableColumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :align="column.align"
            :min-width="column.width"
            header-align="center"
            show-overflow
          >
            <template
              v-if="column.field === 'reconciliationDate'"
              v-slot:default="{ row }"
            >
              {{
                row.reconciliationStartDate + "至" + row.reconciliationEndDate
              }}
            </template>
            <template v-else v-slot:default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
          <vxe-column title="操作" min-width="100" align="center" fixed="right">
            <template v-slot:default="{ row }">
              <vxe-button
                type="text"
                size="small"
                @click="
                  toDetail(
                    {
                      id: row.reconciliationId,
                      title: row.contractName,
                      action: 'view'
                    },
                    'viewReconcoilation'
                  )
                "
                >查看</vxe-button
              >
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          <span>材料信息</span>
          <el-button
            v-if="queryParams.action != 'add'"
            style="float: right"
            color="#1E3485"
            @click="showFilePreview()"
            >预览/下载</el-button
          >
        </template>
        <vxe-table
          border
          show-footer
          min-height="300"
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="rconMaterialTableData"
          :loading="rconMaterialTableLoading"
          :footer-data="rconMaterialTableFooterData"
          size="mini"
        >
          <vxe-column
            type="seq"
            title="序号"
            width="50"
            fixed="left"
            align="center"
          />
          <vxe-column
            v-for="column in rconMaterialTableCloumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :fixed="column.fixed"
            :min-width="column.width"
            :align="column.align"
            show-overflow
          >
            <template v-slot:default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 核对记录 </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="checkTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="核对人" field="cnName" />
          <vxe-column title="核对时间" field="createdAt" />
          <vxe-column title="实时含税总价（元）" field="bizPrice" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="核对说明" field="mark" />
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 结算确认记录（项目部） </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="settlementConfirmTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="确认时间" field="createdAt" />
          <vxe-column title="确认人" field="cnName" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="确认说明" field="mark" />
          <vxe-column title="状态" field="status">
            <template v-slot:default="{ row }">
              <span v-if="row.status == 4">驳回</span>
              <span v-else-if="row.status == 5">通过</span>
              <span v-else>{{ row.status }}</span>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
      <el-card
        v-if="queryParams.action != 'add' && queryParams.action != 'edit'"
        shadow="never"
        style="margin-top: 1%"
      >
        <template #header> 结算确认记录（云采） </template>
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="ycConfirmTableData"
          size="mini"
          align="center"
        >
          <vxe-column title="确认时间" field="createdAt" />
          <vxe-column title="确认人" field="cnName" />
          <vxe-column title="附件" field="file">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.file)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
          <vxe-column title="确认说明" field="mark" />
        </vxe-table>
      </el-card>
    </div>
    <!-- 审批记录 -->
    <div v-if="tabPosition === '1'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>审批记录</template>
        <!-- <div class="examine">
          <img src="@/assets/img/settlement.png" alt="" />
        </div> -->
        <vxe-table
          border
          header-align="center"
          :column-config="{ resizable: true }"
          :row-config="{ isHover: true }"
          :data="examineTableData"
          :loading="examineTableLoding"
          size="mini"
          style="margin-top: 1%"
        >
          <vxe-column title="序号" width="50" align="center" type="seq" />
          <vxe-column
            v-for="column in examineTableColumns"
            :key="column.field"
            :field="column.field"
            :title="column.title"
            :min-width="column.width"
            :align="column.align"
            show-overflow
          >
            <template v-slot:default="{ row }">
              {{ row[column.field] }}
            </template>
          </vxe-column>
          <vxe-column title="审批附件" field="attachList">
            <template v-slot:default="{ row }">
              <div
                v-for="(fileItem, index) in JSON.parse(row.attachList)"
                :key="index"
              >
                <vxe-button @click="downloadFile(fileItem.fileUrl)">
                  {{ fileItem.fileOriginName }}
                </vxe-button>
              </div>
            </template>
          </vxe-column>
        </vxe-table>
      </el-card>
    </div>
    <!-- 核对确认 -->
    <div v-if="tabPosition === '2'">
      <el-card shadow="never" style="margin-top: 1%">
        <template #header>
          {{ examineName() }}
        </template>
        <el-form label-width="150px">
          <el-row>
            <el-col :span="12">
              <el-form-item
                v-if="queryParams.type != '0'"
                label="结算"
                required
              >
                <el-radio-group v-model="confirmModel.reconStatus">
                  <el-radio value="0">确认</el-radio>
                  <el-radio value="1">驳回</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="确认时间">
                <el-date-picker
                  v-model="confirmModel.reconDate"
                  type="date"
                  placeholder="选择日期"
                  style="width: 100%"
                  value-format="YYYY-MM-DD"
                  disabled
                />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="确认人">
                <el-input v-model="confirmModel.reconPerson" disabled />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="确认说明">
                <el-input v-model="confirmModel.reconRemark" type="textarea" />
              </el-form-item>
            </el-col>
          </el-row>
          <!-- 云采确认不展示 -->
          <el-row v-if="queryParams.type != '2'">
            <el-col :span="12">
              <el-form-item label="结算预览下载">
                <el-button
                  color="#1E3485"
                  size="small"
                  @click="showFilePreview()"
                  >预览/下载</el-button
                >
                <span>（注：请下载结算单盖章上传）</span>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col v-if="queryParams.type === '0'" :span="6">
              <el-form-item label="实际含税总价（元）" required>
                <el-input
                  v-model="confirmModel.reconciliationPrice"
                  type="number"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                label="上传附件"
                :required="queryParams.type != '2'"
              >
                <el-upload
                  v-model:file-list="fileList"
                  :action="uploadUrl"
                  :headers="headers"
                  :on-preview="handlePreview"
                  :on-success="handleSuccess"
                  :before-remove="beforeRemove"
                  multiple
                  style="width: 80%"
                >
                  <el-button :icon="Upload" color="#1E3485" size="small"
                    >点击上传</el-button
                  >
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12" style="text-align: center">
              <el-button color="#1E3485" @click="reconConfirmSubmit()"
                >确认</el-button
              >
              <closeTagButton id="closeTagButtonRef" />
            </el-col>
          </el-row>
        </el-form>
      </el-card>
    </div>
    <!-- 弹窗 -->
    <div class="dialogs">
      <salesContractSelectDialog
        :visible="contractSelectDialogVisible"
        @close="closeContractSelectDialog"
        @confirm="contractSelectConfirm"
      />
      <reconciliationSelectDialog
        :visible="reconciliationSelectDialogVisible"
        :contractId="stlmtReconModel.contractId"
        @close="closeReconciliationSelectDialog"
        @confirm="reconciliationSelectConfirm"
      />
      <filePreview
        :visible="filePreviewVisible"
        :fileId="fileId"
        :fileType="fileType"
        :fileUrl="fileUrl"
        @close="closeFilePreview"
      />
    </div>
  </el-form>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import { ElMessage } from "element-plus";
import dayjs from "dayjs";
import { Upload } from "@element-plus/icons-vue";
import type {
  FormInstance,
  UploadUserFile,
  UploadProps,
  UploadFile
} from "element-plus";
import { VxeTablePropTypes } from "vxe-table";
import closeTagButton from "@/components/closeTagButton.vue";
import salesContractSelectDialog from "./dialog/salesContractSelectDialog.vue";
import reconciliationSelectDialog from "./dialog/reconciliationSelectDialog.vue";
import filePreview from "@/components/filePreview.vue";
import { useDetail } from "@/views/ERP_settlement/hooks";
import { useNav } from "@/layout/hooks/useNav";
import { headers, uploadUrl } from "@/api/utils";
import {
  getRecoMaterialDataList,
  saveSettlementData,
  settlementCheck,
  settlementConfirm,
  getSettlementDataInfo,
  getSettlementMaterialDataList,
  getSettlementRecoDataList,
  getConfirmHistoryList,
  settlementYcConfirm,
  getSettlementMaterialDataListFooter,
  stlmtSubmitAudit,
  getProjectSettlementgetSupplyTaxTotalPrice
} from "@/api/ERP_settlement";
import { getAuditHistoryTaskList } from "@/api/ERP_public";
import { ElLoading } from "element-plus";

///////////////////////// 公共 /////////////////////////
// 路由跳转
const { toDetail, router } = useDetail();
const route = useRoute();
const queryParams = route.query;
let examineName = () => {
  switch (queryParams.type) {
    case "0":
      return "核对确认";
    case "1":
      return "结算确认";
    case "2":
      return "云采确认";
  }
};
// 当前登录用户名
const { username } = useNav();
// 默认显示页
let tabPosition = ref("0");
///////////////////////// 数据准备 /////////////////////////
// 详情表单数据
const stlmtReconRef = ref<FormInstance>();
let stlmtReconModel = reactive({
  id: "", // 结算ID
  contractId: "", // 合同ID
  contractNo: "", // 合同编号
  contractName: "", // 合同名称
  projectName: "", // 项目名称
  settlementDate: dayjs().format("YYYY-MM-DD"), // 结算日期
  purchaseDeptName: "", // 采购单位名称
  supplyDeptName: "", // 供货单位名称
  supplierDeptName: "", // 供应商名称
  mark: "", // 备注
  processInstanceId: "", // 审核记录ID
  historySettlementAmount: "" //历史结算金额
});
// 结算对账表
let reconcoloationTableData = ref([]);
let reconcoloationTableLoading = ref(false);
const reconcoloationTableColumns = reactive([
  {
    field: "reconciliationDate",
    title: "对账周期",
    width: 150,
    align: "center"
  },
  {
    field: "supplyNum",
    title: "供货清单",
    width: 150,
    align: "center"
  },
  {
    field: "supplyIncludingTaxTotalPrice",
    title: "含税总价（元）",
    width: 100,
    align: "right"
  },
  {
    field: "reconciliationPrice",
    title: "确认含税总价（元）",
    width: 120,
    align: "right"
  },
  {
    field: "reconciliationConfirmDate",
    title: "对账完成时间",
    width: 150,
    align: "center"
  }
]);
// 结算信息表
let rconMaterialTableData = ref([]);
let rconMaterialTableFooterData = ref<VxeTablePropTypes.FooterData>([]);
let rconMaterialTableLoading = ref(false);
const rconMaterialTableCloumns = reactive([
  {
    field: "materialCode",
    title: "材料编码",
    width: 150,
    align: "center"
  },
  {
    field: "materialName",
    title: "材料名称",
    width: 150,
    align: "center"
  },
  {
    field: "materialSpecs",
    title: "规格",
    width: 150,
    align: "center"
  },
  {
    field: "materialModel",
    title: "型号",
    width: 150,
    align: "center"
  },
  {
    field: "materialUnit",
    title: "单位",
    width: 150,
    align: "center"
  },
  {
    field: "materialBrand",
    title: "品牌",
    width: 150,
    align: "center"
  },
  {
    field: "supplyNum",
    title: "供货数量",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "comfirmSupplyNum",
    title: "确认数量",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "excludingTaxUnitPrice",
    title: "不含税单价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "includingTaxUnitPrice",
    title: "含税单价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "tax",
    title: "税率（%）",
    width: 100,
    align: "center",
    fixed: "right"
  },
  {
    field: "includingTaxTotalPrice",
    title: "含税总价（元）",
    width: 120,
    align: "right",
    fixed: "right"
  },
  {
    field: "reconciliationPrice",
    title: "确认含税总价（元）",
    width: 150,
    align: "right",
    fixed: "right"
  },
  {
    field: "materialMark",
    title: "备注",
    width: 120,
    align: "center",
    fixed: "right"
  }
]);
// 详情表单校验
const rules = reactive({
  contractName: [
    { required: true, message: "请选择销售合同", trigger: "change" }
  ],
  settlementDate: [
    { required: true, message: "请选择结算日期", trigger: "blur" }
  ]
});
// 核对/确认表格
let checkTableData = ref([]);
let settlementConfirmTableData = ref([]);
let ycConfirmTableData = ref([]);
// 审核记录表格
let examineTableData = ref([]);
let examineTableLoding = ref(false);
const examineTableColumns = reactive([
  {
    field: "actName",
    title: "流程节点",
    width: 100,
    align: "center"
  },
  {
    field: "auditDate",
    title: "审批时间",
    width: 100,
    align: "center"
  },
  {
    field: "auditUserName",
    title: "审批人",
    width: 100,
    align: "center"
  },
  {
    field: "auditResultMsg",
    title: "审批结果",
    width: 100,
    align: "center"
  },
  {
    field: "auditMessage",
    title: "审批意见",
    width: 100,
    align: "center"
  }
]);
// 确认表单数据
let confirmModel = reactive({
  reconStatus: "0", // 确认状态
  reconDate: new Date().toISOString().slice(0, 10), // 确认时间
  reconPerson: username.value, // 确认人
  reconRemark: "", // 确认说明
  reconciliationPrice: "", // 确认含税总价（元）
  reconFile: "" // 确认附件
});
// ///////////////////////// 弹窗类 /////////////////////////
// 选择合同弹窗
let contractSelectDialogVisible = ref(false);
function showProjectSelectDialog() {
  contractSelectDialogVisible.value = true;
}
function closeContractSelectDialog(val: boolean) {
  contractSelectDialogVisible.value = val;
}
const contractSelectConfirm = data => {
  stlmtReconModel.contractId = data.contractId;
  stlmtReconModel.contractNo = data.contractNo;
  stlmtReconModel.contractName = data.contractName;
  stlmtReconModel.projectName = data.projectName;
  stlmtReconModel.purchaseDeptName = data.purchaseDeptName;
  stlmtReconModel.supplyDeptName = data.supplyDeptName;
  stlmtReconModel.supplierDeptName = data.supplierDeptName;
  reconcoloationTableData.value = [];
  rconMaterialTableData.value = [];
};
// 项目对账单弹窗
let reconciliationSelectDialogVisible = ref(false);
function showReconciliationSelectDialog() {
  if (stlmtReconModel.contractName === "") {
    ElMessage.error("请先选择销售合同！");
  } else {
    reconciliationSelectDialogVisible.value = true;
  }
}
function closeReconciliationSelectDialog(val: boolean) {
  reconciliationSelectDialogVisible.value = val;
}
const reconciliationSelectConfirm = data => {
  for (let i = 0; i < data.dataList.length; i++) {
    const exists = reconcoloationTableData.value.some(
      item => item.reconciliationId === data.dataList[i].id
    );
    if (exists) {
      ElMessage.error("对账数据: " + data.dataList[i].id + "已存在");
    } else {
      reconcoloationTableData.value.push({
        reconciliationId: data.dataList[i].id,
        ...data.dataList[i]
      });
    }
  }
  getReconciliationTableDataList();
};
// 预览/下载 弹窗
let filePreviewVisible = ref(false);
let fileId = ref("");
let fileType = ref("");
let fileUrl = ref("");
function showFilePreview() {
  fileId.value = queryParams.id as string;
  fileType.value = "pjctsettle";
  filePreviewVisible.value = true;
}
function closeFilePreview(val: boolean) {
  filePreviewVisible.value = val;
}
// 上传按钮&相关事件
let fileList = ref<UploadUserFile[]>([]);
let reconFileList: any = [];
const handlePreview: UploadProps["onPreview"] = (uploadFile: UploadFile) => {
  if (uploadFile.response) {
    const response = uploadFile.response as unknown as any;
    window.open(response.data.url, "_blank");
  } else {
    window.open(uploadFile.url, "_blank");
  }
};
// 文件上传成功,传参赋值，格式修改
const handleSuccess = (fileList: any) => {
  reconFileList.push(fileList.data);
  const formatterObj = [];
  for (let i in reconFileList) {
    let tempvalue: any = {};
    tempvalue.fileUrl = reconFileList[i].url;
    tempvalue.fileSuffix =
      "." +
      reconFileList[i].name.substring(
        reconFileList[i].name.lastIndexOf(".") + 1
      );
    tempvalue.fileOriginName = reconFileList[i].name;
    formatterObj.push(tempvalue);
  }
  confirmModel.reconFile = JSON.stringify(formatterObj);
};
const beforeRemove = (uploadFile: UploadFile) => {
  let fileItems = JSON.parse(confirmModel.reconFile);
  fileItems.forEach((item, index) => {
    if (item.fileOriginName == uploadFile.name) {
      fileItems.splice(index, 1);
    }
  });
  confirmModel.reconFile = fileItems;
  return true;
};
// 表格附件预览
function downloadFile(fileUrl) {
  window.open(fileUrl, "_blank");
}
///////////////////////// 数据请求 /////////////////////////
// 获取对账单绑定的材料列表
async function getReconciliationTableDataList() {
  rconMaterialTableLoading.value = true;
  let params: ApiParams = {};
  params.idList = reconcoloationTableData.value.map(item => item.id);
  try {
    const response: ApiResponse = await getRecoMaterialDataList(params);
    if (response.code === 200) {
      rconMaterialTableData.value = response.data.records;
      getTaxTotalPrice();
    } else {
      ElMessage.error("获取此部分对账单绑定的材料列表失败");
    }
  } catch (error) {
  } finally {
    rconMaterialTableLoading.value = false;
  }
}
// 新增/编辑 - 提交表单
async function submitForm(formEl: FormInstance | undefined) {
  // 表单校验
  if (!formEl) return;
  try {
    const valid = await formEl.validate();
    if (!valid) {
      return false;
    }
  } catch (error) {
    ElMessage.error("输入有误，请检查！");
    return false;
  }
  let params: ApiParams = {
    reconciliationIdList: []
  };
  if (queryParams.id && queryParams.id !== "") {
    params.id = queryParams.id;
    params.historySettlementAmount = stlmtReconModel.historySettlementAmount;
  }
  params.contractMethod = 0;
  params.contractId = stlmtReconModel.contractId;
  params.settlementDate = stlmtReconModel.settlementDate;
  params.mark = stlmtReconModel.mark;
  params.reconciliationIdList = reconcoloationTableData.value.map(
    item => item.reconciliationId
  );
  params.reconciliationStartDate =
    reconcoloationTableData.value[0].reconciliationStartDate;
  params.reconciliationEndDate =
    reconcoloationTableData.value[0].reconciliationEndDate;
  try {
    const response: ApiResponse = await saveSettlementData(params);
    if (response.code === 200) {
      ElMessage.success("提交成功");
      document.getElementById("closeTagButtonRef").click();
    } else {
      ElMessage.error("提交失败");
    }
  } catch (error) {}
}
// 核对确认
async function reconConfirmSubmit() {
  if (confirmModel.reconFile == "" && queryParams.type != "2") {
    ElMessage.error("请先上传附件！");
    return false;
  }
  let params: ApiParams = {};
  params.id = queryParams.id;
  // 核对确认
  if (queryParams.type === "0") {
    if (confirmModel.reconciliationPrice === "") {
      ElMessage.error("请输入含税总价！");
      return false;
    }
    params.reconciliationPrice = confirmModel.reconciliationPrice;
    params.checkMark = confirmModel.reconRemark;
    params.checkFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await settlementCheck(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
  // 结算确认
  if (queryParams.type === "1") {
    params.isConfirmReconciliation =
      confirmModel.reconStatus === "0" ? true : false;
    params.confirmReconciliationMark = confirmModel.reconRemark;
    params.confirmReconciliationFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await settlementConfirm(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
  // 云采确认
  if (queryParams.type === "2") {
    params.confirmReconciliationMark = confirmModel.reconRemark;
    params.confirmReconciliationFile = confirmModel.reconFile;
    try {
      const response: ApiResponse = await settlementYcConfirm(params);
      if (response.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
      } else {
        ElMessage.error("提交失败: " + response.msg);
      }
    } catch (error) {}
  }
}
// 获取结算单详情
async function getSettlementDetail() {
  let params: ApiParams = {};
  params.id = queryParams.id;
  params.contractMethod = 0;
  try {
    const response: ApiResponse = await getSettlementDataInfo(params);
    if (response.code === 200) {
      // 表单部分
      stlmtReconModel.id = response.data.id;
      stlmtReconModel.contractId = response.data.contractId;
      stlmtReconModel.contractNo = response.data.contractNo;
      stlmtReconModel.contractName = response.data.contractName;
      stlmtReconModel.projectName = response.data.projectName;
      stlmtReconModel.settlementDate = response.data.settlementDate;
      stlmtReconModel.purchaseDeptName = response.data.purchaseDeptName;
      stlmtReconModel.supplyDeptName = response.data.supplyDeptName;
      stlmtReconModel.supplierDeptName = response.data.supplierDeptName;
      stlmtReconModel.mark = response.data.mark;
      stlmtReconModel.processInstanceId = response.data.processInstanceId;
      stlmtReconModel.historySettlementAmount =
        response.data.historySettlementAmount;
    } else {
      ElMessage.error("获取结算单详情失败: " + response.msg);
    }
  } catch (error) {}
}
// 获取核对表记录
async function getConfirmTablesData(type: string) {
  let params: ApiParams = {};
  params.bizId = queryParams.id;
  params.type = type;
  // 核对确认表
  if (type === "0") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    checkTableData.value = response.data;
  }
  // 结算确认表
  if (type === "1") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    settlementConfirmTableData.value = response.data;
  }
  // 云采确认表
  if (type === "3") {
    const response: ApiResponse = await getConfirmHistoryList(params);
    ycConfirmTableData.value = response.data;
  }
}
// 获取绑定的对账单
async function getSettlementOrderList() {
  reconcoloationTableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = 1;
  params.pageSize = 999;
  params.reconciliationSettlementId = queryParams.id;
  try {
    const response: ApiResponse = await getSettlementRecoDataList(params);
    if (response.code === 200) {
      reconcoloationTableData.value = response.data.records;
      let sum = 0;
      for (let i in response.data.records) {
        sum += Number(response.data.records[i].reconciliationPrice);
      }
      confirmModel.reconciliationPrice = sum.toString();
    } else {
      ElMessage.error("获取绑定的对账单失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    reconcoloationTableLoading.value = false;
  }
}
// 获取绑定的材料列表
async function getSettlementMaterialList() {
  rconMaterialTableLoading.value = true;
  let params: ApiParams = {};
  params.pageIndex = 1;
  params.pageSize = 999;
  params.reconciliationSettlementId = queryParams.id;
  try {
    const response: ApiResponse = await getSettlementMaterialDataList(params);
    if (response.code === 200) {
      rconMaterialTableData.value = response.data.records;
      if (rconMaterialTableData.value.length != 0) {
        getReconciliationTableDataListFooter();
      }
    } else {
      ElMessage.error("获取材料列表失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    rconMaterialTableLoading.value = false;
  }
}
// 获取绑定的材料列表footer数据
function getReconciliationTableDataListFooter() {
  // 改为前端计算 edit by YUM 241008
  rconMaterialTableFooterData.value = [
    {
      supplyNum: computed(() => {
        return rconMaterialTableData.value.reduce((total, row) => {
          return total + (Number(row.supplyNum) || 0);
        }, 0);
      }),
      comfirmSupplyNum: computed(() => {
        return rconMaterialTableData.value.reduce((total, row) => {
          return total + (Number(row.comfirmSupplyNum) || 0);
        }, 0);
      }),
      includingTaxTotalPrice: computed(() => {
        return rconMaterialTableData.value.reduce((total, row) => {
          return total + (Number(row.includingTaxTotalPrice) || 0);
        }, 0);
      }),
      reconciliationPrice: computed(() => {
        return rconMaterialTableData.value.reduce((total, row) => {
          return total + (Number(row.reconciliationPrice) || 0);
        }, 0);
      })
    }
  ];
}
// 获取审批记录
async function getExamineTableData() {
  examineTableLoding.value = true;
  let params: ApiParams = {};
  params.processInstanceId = stlmtReconModel.processInstanceId;
  try {
    const response: ApiResponse = await getAuditHistoryTaskList(params);
    if (response.code === 200) {
      examineTableData.value = response.data;
    } else {
      ElMessage.error("获取审批记录失败: " + response.msg);
    }
  } catch (error) {
  } finally {
    examineTableLoding.value = false;
  }
}
///保存并提交
async function saveOrSubmit(formEl: FormInstance | undefined) {
  // 表单校验
  if (!formEl) return;
  try {
    const valid = await formEl.validate();
    if (!valid) {
      return false;
    }
  } catch (error) {
    ElMessage.error("输入有误，请检查！");
    return false;
  }
  let params: ApiParams = {
    reconciliationIdList: []
  };
  if (queryParams.id && queryParams.id !== "") {
    params.id = queryParams.id;
    params.historySettlementAmount = stlmtReconModel.historySettlementAmount;
  }
  params.contractMethod = 0;
  params.contractId = stlmtReconModel.contractId;
  params.settlementDate = stlmtReconModel.settlementDate;
  params.mark = stlmtReconModel.mark;
  params.reconciliationIdList = reconcoloationTableData.value.map(
    item => item.reconciliationId
  );
  params.reconciliationStartDate =
    reconcoloationTableData.value[0].reconciliationStartDate;
  params.reconciliationEndDate =
    reconcoloationTableData.value[0].reconciliationEndDate;
  try {
    let loadingInstance = ElLoading.service({
      lock: true,
      text: "单据提交中",
      background: "rgba(0, 0, 0, 0.7)"
    });
    const response: ApiResponse = await saveSettlementData(params);
    if (response.code === 200) {
      let param: ApiParams = {};
      param.id = response.data;
      const res: ApiResponse = await stlmtSubmitAudit(param);
      if (res.code === 200) {
        ElMessage.success("提交成功");
        document.getElementById("closeTagButtonRef").click();
        loadingInstance.close();
      } else {
        ElMessage.error("提交失败：" + res.msg);
        loadingInstance.close();
      }
    } else {
      ElMessage.error("提交失败");
      loadingInstance.close();
    }
  } catch (error) {}
}
async function getTaxTotalPrice() {
  let arr = [];
  for (let i in reconcoloationTableData.value) {
    arr.push(reconcoloationTableData.value[i].id);
  }
  let params: ApiParams = {};
  params.contractId = stlmtReconModel.contractId;
  const response: ApiResponse =
    await getProjectSettlementgetSupplyTaxTotalPrice(params);
  if (response.code === 200) {
    stlmtReconModel.historySettlementAmount = response.data;
  }
}
///////////////////////// 公共 /////////////////////////
onMounted(async () => {
  if (queryParams.action === "examine") {
    tabPosition.value = "2";
  }
  if (queryParams.action != "add") {
    await getSettlementDetail();
    await getSettlementOrderList();
    await getSettlementMaterialList();
    await getConfirmTablesData("0");
    await getConfirmTablesData("1");
    await getConfirmTablesData("3");
    //getTaxTotalPrice();
  }
});
</script>

<style lang="scss" scoped>
.examine {
  display: grid;
  place-items: center;
  img {
    height: 15vh;
  }
}
</style>
